const fs = require('fs');
const Promise = require('bluebird');
const request = require('request');
const emoji = require('node-emoji');
const axios = require('axios');

module.exports = function (settings, storage) {
  let getUserUrl = function () {
    return storage.config.domain + '/my_orders';
  }
  let getAgencyUrl = function (taobaoTradeParentId) {
    return storage.config.domain + '/fans_orders?taobaoTradeParentId=' + taobaoTradeParentId;
  }
  let getPartnerUrl = function (taobaoTradeParentId) {
    return storage.config.domain + '/partner_orders?taobaoTradeParentId=' + taobaoTradeParentId;
  }
  let getJdUserUrl = function () {
    return storage.config.domain + '/my_orders?type=jd';
  }
  let getJdAgencyUrl = function (orderId) {
    return storage.config.domain + '/fans_orders?orderId=' + orderId + '&type=jd';
  }
  let getJdPartnerUrl = function (orderId) {
    return storage.config.domain + '/partner_orders?orderId=' + orderId + '&type=jd';
  }

  return {
    /**
     * 处理文本事件
     */
    handle: function (message, req, res) {
      let text = emoji.strip(message.Content);
      let openid = message.FromUserName;

      let {Users, TaokeOrders, UserOrders, JDUserOrders, JDOrders, UsersTexts, UsersSearchs, AutoResponses} = storage.models;
      UsersTexts.create({
        openid: openid,
        text: text
      });

      // 自动回复代码
      // AutoResponses.findOne({where: {keyword: text}}).then(function (response) {
      //     if (response) {
      //         return res.reply(response.response);
      //     } else {
      //
      //     }
      // });

      //判断是不是京东
      if (text.indexOf('.jd.com/') != -1) {
        let arr;
        if (text.indexOf('item.m.jd.com') != -1) {
          arr = text.match(/[http|https]\:\/\/item\.m\.jd\.com\/product\/(\d+)\.html/);
        } else if (text.indexOf('item.jd.com') != -1) {
          arr = text.match(/[http|https]\:\/\/item\.jd\.com\/(\d+)\.html/);
        }
        if (arr && arr[1]) {
          let id = arr[1];
          return storage.spider.getJdGoodsById({id: id}).then(function (goods) {
            if (!goods) {
              return res.reply('获取商品失败');
            }
            return Users.findOne({where: {openid: openid}}).then(function (user) {
              return Promise.resolve().then(function () {
                if (user && user.level == 'Partner') {
                  return Promise.props({
                    user: user,
                    agency: user,
                    partner: user
                  });
                } else if (user && user.level == 'Agency') {
                  return Promise.props({
                    user: user,
                    agency: user,
                    partner: Users.findOne({where: {id: user && user.partner_id || 1}})
                  });
                } else {
                  return Promise.props({
                    user: user,
                    agency: Users.findOne({where: {id: user && user.agency_id || 1}}),
                    partner: Users.findOne({where: {id: user && user.partner_id || 1}})
                  });
                }
              }).then(function ({user, agency, partner}) {
                return storage.spider.jdApplyEvent(goods, agency.jd_pid ? agency : partner).then(function (event) {
                  if (!event) {
                    console.error('京东申请商品失败', goods);
                    return storage.spider.getShortUrl(storage.config.domain + '?keyword=' + goods.skuName).then(function (shortUrl) {
                      return res.reply(goods.skuName + '\n' + '点击链接搜索淘宝相似商品:' + shortUrl);
                    });
                  }
                  return res.reply('点击下面链接购买商品可获取返利' + ((goods.wlCommission * agency.order_return_scale / 100).toFixed(2)) +
                    '元(以实际为准)\n下单后把订单号发送到公众号可获取返现，如果购物车中已经有该商品，请先删除' + '\n' + event.shotCode);
                });
              });
            });
          });
        }

        return res.reply('获取商品失败，请分享京东商品详情链接...');
      }

      //全数字，订单编号
      if (/^\d+$/.test(text) && text.length > 10) {
        //京东订单
        if (text.length <= 12) {
          return JDUserOrders.findOne({where: {orderId: text}}).then(function (userOrder) {
            if (userOrder) {
              return Users.findOne({where: {openid: openid}}).then(function (user) {
                if (user.level == 'Partner') {
                  return res.reply(text + '\n京东订单已经录入, 点击下面的链接查看.\n' + getJdPartnerUrl(text));
                } else if (user.level == 'Agency') {
                  return res.reply(text + '\n京东订单已经录入, 点击下面的链接查看.\n' + getJdAgencyUrl(text));
                } else {
                  return res.reply(text + '\n京东订单已经录入, 点击下面的链接查看.\n' + getJdUserUrl());
                }
              });
            }
            return JDOrders.findOne({where: {orderId: text}}).then(function (jdOrder) {
              //订单状态是否失效
              if (jdOrder.ynDetail === '取消订单' || jdOrder.ynName === '无效') {
                return res.reply(text + '\n京东订单失效.');
              }
              return Users.findOne({where: {openid: openid}}).then(function (user) {
                if (!user) {
                  console.error('京东订单录入, 用户不存在...');
                  return res.reply('京东订单录入, 用户不存在...');
                }
                return JDUserOrders.create({
                  orderId: text,
                  user_id: user.id,
                  status: jdOrder ? 'Related' : 'Pending'
                }).then(function (userOrder) {
                  res.reply(text + '\n京东订单录入成功, 可在用户中心查看订单或点击下面的链接查看.\n' + getJdUserUrl());

                  return Promise.resolve().then(function () {
                    if (user.level == 'Partner') {
                      return Promise.props({
                        user: user,
                        agency: user,
                        partner: user
                      });
                    } else if (user.level == 'Agency') {
                      return Promise.props({
                        user: user,
                        agency: user,
                        partner: Users.findOne({where: {id: user && user.partner_id || 1}})
                      });
                    } else {
                      return Promise.props({
                        user: user,
                        agency: Users.findOne({where: {id: user && user.agency_id || 1}}),
                        partner: Users.findOne({where: {id: user && user.partner_id || 1}})
                      });
                    }
                  }).then(function ({user, agency, partner}) {
                    let data = {
                      user_id: user.id,
                      // pay_amount: storage.spider.getRealFanli({
                      //     fee: parseFloat(taokeOrder.feeString),
                      //     user: user,
                      //     agency: agency
                      // }),
                      status: 'Related'
                    };
                    if (user.inviter_id && agency.inviter_scale > 0) {
                      data.inviter_id = user.inviter_id;
                      // data.inviter_pay_amount = (parseFloat(taokeOrder.feeString) * agency.inviter_scale / 100).toFixed(2);
                    }
                    return JDOrders.update(data, {where: {id: jdOrder.id}}).then(function () {
                      return JDOrders.amountV2(jdOrder.id);
                    }).then(function () {
                      let replyText = '京东订单可返 ' + jdOrder.pay_amount.toFixed(2) + ' 元, 确认收货后可在用户中心申请提现';
                      if (partner.id != 1001) {
                        replyText += '\n尊敬的各位便宜咯用户您好！便宜咯不日即将迁移至呆萌价为了确保您的账户资金不受损失 ！！\n' +
                          '请速联系客服为您升级办理（客服微信：Y312424930）'
                      }
                      res.reply(replyText);
                      // storage.wechatInstance.shopWebApi.sendText(user.openid, replyText, function (err) {
                      //   if (err) {
                      //     console.error('\n', err.stack || err.message);
                      //   }
                      // });
                      // storage.wechatInstance.shopWebApi.sendText(partner.openid, user.nickname + '\n' + replyText + '\n' + getPartnerUrl(text), function (err) {
                      //   if (err) {
                      //     console.error('\n', err.stack || err.message);
                      //   }
                      // });
                    });
                  });
                });
              });
            });
          });
        }
        //淘宝订单
        if (text.length >= 13) {
          return UserOrders.findOne({where: {taobaoTradeParentId: text}}).then(function (userOrder) {
            if (userOrder) {
              return Users.findOne({where: {openid: openid}}).then(function (user) {
                if (user.level == 'Partner') {
                  return res.reply(text + '\n订单已经录入, 点击下面的链接查看.\n' + getPartnerUrl(text));
                } else if (user.level == 'Agency') {
                  return res.reply(text + '\n订单已经录入, 点击下面的链接查看.\n' + getAgencyUrl(text));
                } else {
                  return res.reply(text + '\n订单已经录入, 点击下面的链接查看.\n' + getUserUrl());
                }
              });
            }
            return TaokeOrders.findAll({where: {taobaoTradeParentId: text}}).then(function (taokeOrders) {
              //订单状态是否全部失效
              if (taokeOrders && taokeOrders.length) {
                let isDeactivated = true;
                for (let i in taokeOrders) {
                  if (taokeOrders[i].payStatus != '订单失效') {
                    isDeactivated = false;
                  }
                }
                if (isDeactivated) {
                  return res.reply(text + '\n订单失效.');
                }
              }

              return Users.findOne({where: {openid: openid}}).then(function (user) {
                if (!user) {
                  console.error('订单录入, 用户不存在...');
                  return res.reply('订单录入, 用户不存在...');
                }
                return UserOrders.create({
                  taobaoTradeParentId: text,
                  user_id: user.id,
                  status: (taokeOrders && taokeOrders.length) ? 'Related' : 'Pending'
                }).then(function (userOrder) {
                  res.reply(text + '\n订单录入成功, 可在用户中心查看订单或点击下面的链接查看.\n' + getUserUrl());

                  if (taokeOrders && taokeOrders.length) {
                    return Promise.resolve().then(function () {
                      if (user.level == 'Partner') {
                        return Promise.props({
                          user: user,
                          agency: user,
                          partner: user
                        });
                      } else if (user.level == 'Agency') {
                        return Promise.props({
                          user: user,
                          agency: user,
                          partner: Users.findOne({where: {id: user && user.partner_id || 1}})
                        });
                      } else {
                        return Promise.props({
                          user: user,
                          agency: Users.findOne({where: {id: user && user.agency_id || 1}}),
                          partner: Users.findOne({where: {id: user && user.partner_id || 1}})
                        });
                      }
                    }).then(function ({user, agency, partner}) {
                      let totalPay = 0;
                      return Promise.mapSeries(taokeOrders, function (taokeOrder) {
                        if (taokeOrder.payStatus === '订单失效') {
                          return;
                        }
                        let data = {
                          user_id: user.id,
                          // pay_amount: storage.spider.getRealFanli({
                          //     fee: parseFloat(taokeOrder.feeString),
                          //     user: user,
                          //     agency: agency
                          // }),
                          status: 'Related'
                        };
                        if (user.inviter_id && agency.inviter_scale > 0) {
                          data.inviter_id = user.inviter_id;
                          // data.inviter_pay_amount = (parseFloat(taokeOrder.feeString) * agency.inviter_scale / 100).toFixed(2);
                        }
                        return TaokeOrders.update(data, {where: {id: taokeOrder.id}}).then(function () {
                          return TaokeOrders.amountV2(taokeOrder.id).then(function (result) {
                            if (result.success && taokeOrder.pay_amount > 0) {
                              totalPay += parseFloat(taokeOrder.pay_amount);
                            }
                          });
                        });
                      }).then(function () {
                        if (totalPay > 0) {
                          let replyText = '订单可返 ' + totalPay.toFixed(2) + ' 元';

                          if (partner.return_qrcode && (partner.return_quick || (partner.first_quick && user.order_count === 0))) {
                            let sendQrcode = function (qrcode_mediaid) {
                              return storage.wechatInstance.shopWebApi.sendImage(openid, qrcode_mediaid, function (err, result) {
                                if (err) {
                                  console.error('\n', err.stack || err.message);
                                }
                              });
                            }
                            if (partner.return_qrcode_mediaid) {
                              sendQrcode(partner.return_qrcode_mediaid);
                            } else {
                              let qrcodeTo = storage.paths.qrcode + 'return_qrcode_' + user.id + '_' + (new Date().getTime()) + '.png';
                              new Promise(function (resolve) {
                                request.get(partner.return_qrcode).on('end', function () {
                                  resolve();
                                }).pipe(fs.createWriteStream(qrcodeTo));
                              }).then(function () {

                                return storage.wechatInstance.shopWebApi.uploadMaterial(qrcodeTo, 'image', function (err, result) {
                                  console.log('上传永久图片', result);

                                  if (err) {
                                    console.error('\n', err.stack || err.message);
                                  }
                                  storage.models.Users.update({return_qrcode_mediaid: result.media_id}, {where: {id: partner.id}});

                                  return sendQrcode(result.media_id);
                                });
                              });
                            }
                          } else {
                            replyText = replyText + ', 确认收货后可在用户中心申请提现';
                          }
                          if (partner.id != 1001) {
                            replyText += '\n尊敬的各位便宜咯用户您好！便宜咯不日即将迁移至呆萌价为了确保您的账户资金不受损失 ！\n' +
                              '请速联系客服为您升级办理（客服微信：Y312424930）'
                          }

                          res.reply(replyText);
                          // storage.wechatInstance.shopWebApi.sendText(user.openid, replyText, function (err) {
                          //   if (err) {
                          //     console.error('\n', err.stack || err.message);
                          //   }
                          // });
                          // storage.wechatInstance.shopWebApi.sendText(partner.openid, user.nickname + '\n' + replyText + '\n' + getPartnerUrl(text), function (err) {
                          //   if (err) {
                          //     console.error('\n', err.stack || err.message);
                          //   }
                          // });
                        }
                      });
                    });
                  }
                });
              });
            });
          });
        }
      }

      //获取标题，返回搜索连接
      let handleByTitle = function () {
        let title = text;
        let arr = text.match(/（(.{6,})?）/i);
        if (arr && arr[1]) {
          title = arr[1];
        } else {
          arr = text.match(/【(.{6,})?】/i);
          if (arr && arr[1]) {
            title = arr[1];
          }
        }
        // return storage.spider.getShortUrl(storage.config.domain + '?keyword=' + title).then(function (shortUrl) {
        //   return res.reply(title + '\n' + '点击链接搜索商品:' + shortUrl);
        // });
      }


      if (!/^http.+$/.test(text)) {
        handleByTitle();
      } else {
        // res.reply('商品获取中...');
      }

      let handleByApi = function (url, title) {
        return Users.findOne({where: {openid: openid}}).then(function (user) {
          return Promise.props({
            agency: Users.findOne({where: {id: user && user.agency_id || 1}}),
            partner: Users.findOne({where: {id: user && user.partner_id || 1}})
          }).then(function (data) {
            data.user = user;
            return data;
          });
        }).then(function ({user, agency, partner}) {
          let session = partner.session;
          let site_id = agency.mediumId || partner.mediumId;
          let adzone_id = agency.adPositionId || partner.adPositionId;
          if (!session) {
            return {success: false};
          }
          return storage.utils.getRealUrl(url).then(function (realUrl) {
            console.log({
              goods_id: storage.utils.getQueryString(realUrl, 'id'),
              session: session,
              site_id: site_id,
              adzone_id: adzone_id
            });
            // http://www.qilacps.com/api/services/v1/taobao/wx_data?sskey=ss123456
            return axios.post('http://pyl.kkdd789.com:19489/api/services/v1/taobao/wx_data?sskey=ss123456', {
              goods_id: storage.utils.getQueryString(realUrl, 'id'),
              session: session,
              site_id: site_id,
              adzone_id: adzone_id
            }).then((response) => {
              let data = response.data && response.data.data;
              console.log('data', response.data);
              if (data && data.tkl) {
                let text = '【商品】' + data.text;
                if (data.coupon_price) {
                  text += '\n领' + data.coupon_price + '元券，券后【' + data.price + '元】'
                } else {
                  text += '\n价格: 【' + data.price + '元】'
                }

                text += '\n【口令】' + data.tkl;
                text += '\n复制这条信息，打开☞手机淘宝☜即可查看并下单！';

                let price = parseFloat(data.price);
                let rate = parseFloat(data.commission);
                let fee = (price * rate / 100);
                let fanli = storage.spider.getUserFanli({
                  fee: fee,
                  agency: agency
                });
                if (fanli && parseFloat(fanli) > 0) {
                  text += '\n\n【预计返现】' + fanli + '元(以实际为准)\n下单后把订单号发送到公众号可获取返现，如果购物车中已经有该商品，请先删除后复制口令下单';
                }
                if (partner && partner.id && partner.id != 1001 && partner.id != 15705) {
                  text += '\n\n尊敬的各位便宜咯用户您好！便宜咯不日即将迁移至呆萌价为了确保您的账户资金不受损失 ！！\n' +
                    '请速联系客服为您升级办理（客服微信：Y312424930）'
                }
                res.reply(text);
                // storage.wechatInstance.shopWebApi.sendText(openid, text, function (err) {
                //   if (err) {
                //     console.error('\n', err.stack || err.message);
                //   }
                // });
                return {success: true};
              }
              return {success: false};
            }).catch((err) => {
              console.log('========== abc123');
              if (err) {
                console.error('\n', err.stack || err.message);
              }
              return {success: false};
            });
          });
        });
      }

      let handle = function (url, title, retry) {
        let time = new Date().getTime();
        return handleByApi(url, title).then(function (result) {
          if (result && result.success) {
            return result;
          }
          return storage.spider.getGoodsByUrl({url: url, title: title, user_id: openid}).then(function (result) {
            console.error('=== get goods time', (new Date().getTime() - time));

            if (result.success) {
              let goods = result.data;
              if (goods.status != 'Active') {
                return false;
              }
              return storage.spider.handleShare({
                goods: goods,
                openid: openid
              }).then(function ({user, agency, text}) {
                console.error('=== handleShare time', (new Date().getTime() - time));

                if (user) {
                  UsersSearchs.destroy({
                    where: {
                      keyword: '',
                      goods_id: goods.auctionId,
                      user_id: user.id
                    }
                  }).then(function () {
                    return UsersSearchs.create({
                      keyword: '',
                      goods_id: goods.auctionId,
                      user_id: user.id,
                      agency_id: user.agency_id
                    });
                  }).catch(function (err) {
                    if (err) {
                      console.error('保存搜索异常:Text', {
                        keyword: '',
                        goods_id: goods.auctionId,
                        user_id: user.id,
                        agency_id: user.agency_id
                      });
                    }
                  });
                }


                let price = goods.quanPrice || goods.zkPrice;
                let rate = goods.commission || goods.tkRate;
                let fee = (price * rate / 100);
                let fanli = storage.spider.getUserFanli({
                  fee: fee,
                  agency: agency
                });
                if (fanli > 0) {
                  res.reply(text + '\n\n【预计返现】' + fanli + '元(以实际为准)\n下单后把订单号发送到公众号可获取返现，如果购物车中已经有该商品，请先删除后复制口令下单');
                  // storage.wechatInstance.shopWebApi.sendText(openid, text + '\n\n【预计返现】' + fanli + '元(以实际为准)\n下单后把订单号发送到公众号可获取返现，如果购物车中已经有该商品，请先删除后复制口令下单', function (err) {
                  //   console.error('=== sendText time', (new Date().getTime() - time));
                  //
                  //   if (err) {
                  //     console.error('\n', err.stack || err.message);
                  //   }
                  // });
                } else {
                  storage.wechatInstance.shopWebApi.sendText(openid, text, function (err) {
                    console.error('=== sendText time', (new Date().getTime() - time));

                    if (err) {
                      console.error('\n', err.stack || err.message);
                    }
                  });
                }
              });
            } else {
              console.log('wechat text', result.message, 'retry', retry);

              let arr = text.match(/(http.*?)(，|\s|$)/i);
              if (arr && arr[1]) {
                if (!retry) {
                  coverKl(1);
                }
              }
            }
          });
        });
      }

      let restoreTaokouFailed = function () {
        let sendMedia = function (mediaid) {
          return storage.wechatInstance.shopWebApi.sendImage(openid, mediaid, function (err, result) {
            if (err) {
              console.error('\n', err.stack || err.message);
            }
          });
        }

        let copylink_course_media_id = storage.cache.settings.value('copylink_course_media_id');
        if (copylink_course_media_id) {
          return sendMedia(copylink_course_media_id);
        }

        let copylinkCourseImagePath = storage.paths.download + 'copylink_course_image.png';
        storage.wechatInstance.shopWebApi.uploadMaterial(copylinkCourseImagePath, 'image', function (err, result) {
          console.log('上传永久图片', result);
          if (err) {
            console.error('\n', err.stack || err.message);
          } else {
            sendMedia(result.media_id);
            storage.models.Settings.update({value: result.media_id}, {where: {name: 'copylink_course_media_id'}}).then(function () {
              storage.redis.pub.publish('settings_update', 'settings_update');
            });
          }
        });
      }

      let coverKl = function (retry) {
        if (text.indexOf('￥') != -1 || text.indexOf('《') != -1 || text.indexOf('€') != -1 || text.indexOf('$') != -1 || text.indexOf('₤') != -1 || text.indexOf('¢') != -1 || text.indexOf('₳') != -1 || text.indexOf('₴') != -1) {
          return storage.taobaoApi.parseTkl(text).then(function (result) {
            if (result && result.url) {
              let title;
              let arr = result.content.match(/（(.*?)）/i);
              if (arr && arr.length > 1) {
                title = arr[1];
              }
              return handle(result.url, title, retry);
            } else {
              restoreTaokouFailed();
            }
          });
        } else {
          restoreTaokouFailed();
        }
      }

      let arr = text.match(/(http.*?)(，|\s|$)/i);
      if (arr && arr[1]) {
        let url = arr[1];
        return handle(url);
      } else {
        coverKl();
      }

      // console.log('transfer2CustomerService');
      // return res.transfer2CustomerService();
    }
  }
}
